package com.shengyin.ec.util;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class UploadFileUtil {
	
	
	public static String  Upload(HttpServletRequest request, MultipartFile file,String uploadFolder) {
		String fpath=null;
		if(file!=null&&!file.isEmpty()){
			try {
			String fileName = file.getOriginalFilename(); 			
			/** 
			                     
			* 获取文件后缀 
		                   
			*/
		                   
			String[] suffixs=fileName.split("\\."); 
		                    
			String suffix = "."+suffixs[suffixs.length-1];
			
			Calendar calendar=Calendar.getInstance();
			String date=new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
			
			byte[] bytes;
			String uploadPath=null;
				bytes = file.getBytes();
			
				if("goods".equals(uploadFolder)){
					uploadPath = "upload/"+fileName; 
				}else{
					uploadPath="upload/"+uploadFolder+"/"+date+"/"+fileName;
				}
					
			File filePath = new File(request.getSession().getServletContext().getRealPath(uploadPath)); 
			
			if(!filePath.getParentFile().exists()){
				filePath.getParentFile().mkdirs();
			}
			FileCopyUtils.copy(bytes, filePath);
			fpath=uploadPath;
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
		return fpath ;
	}

	public static void createPreviewImage(String srcFile, String destFile) {   
        try {   
            File fi = new File(srcFile); // src   
            File fo = new File(destFile); // dest   
            BufferedImage bis = ImageIO.read(fi);   
            final int IMAGE_SIZE = 120;  
            int w = bis.getWidth();   
            int h = bis.getHeight();   
            double scale = (double) w / h;   
            int nw = IMAGE_SIZE; // final int IMAGE_SIZE = 120;   
            int nh = (nw * h) / w;   
            if (nh > IMAGE_SIZE) {   
                nh = IMAGE_SIZE;   
                nw = (nh * w) / h;   
            }   
            double sx = (double) nw / w;   
            double sy = (double) nh / h;   
  
            AffineTransform transform=new  AffineTransform();
            transform.setToScale(sx, sy);   
            AffineTransformOp ato = new AffineTransformOp(transform, null);   
            BufferedImage bid = new BufferedImage(nw, nh,   
                    BufferedImage.TYPE_3BYTE_BGR);   
            ato.filter(bis, bid);   
            ImageIO.write(bid, " jpeg ", fo);   
        } catch (Exception e) {   
            e.printStackTrace();   
            throw new RuntimeException(   
                    " Failed in create preview image. Error:  "  
                            + e.getMessage());   
        }   
    }  
	
	/**
     * 生成缩略图
     * @param srcImageFile 源图片文件的File实例      File file = new File("文件名");
     * @param dstImageFileName 待生成的缩略图片完整路径(生成的格式为：image/jpeg);
     * @throws Exception
     */
    public static void makeSmallImage(File srcImageFile,String dstImageFileName)  {
        FileOutputStream fileOutputStream = null;
        JPEGImageEncoder encoder = null;
        BufferedImage tagImage = null;
        Image srcImage = null;
        try{
            srcImage = ImageIO.read(srcImageFile);
            int srcWidth = srcImage.getWidth(null);//原图片宽度
            int srcHeight = srcImage.getHeight(null);//原图片高度
            int dstMaxSize = 120;//目标缩略图的最大宽度/高度，宽度与高度将按比例缩写
            int dstWidth = srcWidth;//缩略图宽度
            int dstHeight = srcHeight;//缩略图高度
            float scale = 0;
            //计算缩略图的宽和高
            if(srcWidth>dstMaxSize){
                dstWidth = dstMaxSize;
                scale = (float)srcWidth/(float)dstMaxSize;
                dstHeight = Math.round((float)srcHeight/scale);
            }
            srcHeight = dstHeight;
            if(srcHeight>dstMaxSize){
                dstHeight = dstMaxSize;
                scale = (float)srcHeight/(float)dstMaxSize;
                dstWidth = Math.round((float)dstWidth/scale);
            }
            //生成缩略图
            tagImage = new BufferedImage(dstWidth,dstHeight,BufferedImage.TYPE_INT_RGB);
            tagImage.getGraphics().drawImage(srcImage,0,0,dstWidth,dstHeight,null);
				fileOutputStream = new FileOutputStream(dstImageFileName);
            encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
            encoder.encode(tagImage);
            fileOutputStream.close();
            fileOutputStream = null;
        }
        catch (FileNotFoundException e){
        	
        } catch (ImageFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        finally{
            if(fileOutputStream!=null){
                try{
                    fileOutputStream.close();
                }catch(Exception e){
                }
                fileOutputStream = null;
            }
            encoder = null;
            tagImage = null;
            srcImage = null;
            System.gc();
        }
    }


}
